<template>
<div class="box">
  <div class="info">
    <b @click="prevMonth"></b>
    <span>{{time.year}} 年</span>
    <span>{{time.month}} 月</span>
    <b @click="nextMonth"></b>
  </div>
  <ul
    :style="ulStyle">
    <li v-for="item of ['日','一','二','三','四','五','六']">{{item}}</li>
    <li
      v-for="item of indent"
      class="empty"></li>
    <li
      v-for="(item, i) of dateNum"
      :data-i="i"
      :class="i + 1 === time.date ? 'checked' : ''"
      @click="clickDate">{{i + 1}}</li>
  </ul>
  <div class="ctrl">
    <div @click="ok">确定</div>
    <div @click="no">取消</div>
  </div>
</div>
</template>

<script>
const isLeapYear = year => (
  (year % 4 == 0) && (year % 100 != 0) || year % 400 == 0
);
const getDayNumList = year => {
  const feb = isLeapYear(year) ? 29 : 28;
  return [31,feb,31,30,31,30,31,31,30,31,30,31];
};
const getStartDay = o => {
  const leap = isLeapYear(o.year);
  const days = getDayNumList(o.year);
  let sum = 0;
  for (let i = 1; i < o.year; i++) {
    sum += (isLeapYear(i) ? 366 : 365);
  }
  for (let i = 1; i < o.month; i++) {
    sum += days[i];
  }
  return (sum + 1) % 7; // 0 is Sunday
};
const getEndDate = o => {
  return getDayNumList(o.year)[o.month - 1];
};

export default {
  props : ['callback', 'outTime'],
  data () {
    return {
      indent  : getStartDay(this.outTime),
      time    : this.outTime,
      dateNum : getEndDate(this.outTime),
      ulStyle : {
        height : 0,
        lineHeight : 0,
      },
    };
  },
  mounted () {
    const box = document.querySelector('.box');
    const cellHeight = box.clientWidth / 7;
    this.ulStyle.lineHeight = cellHeight +'px';
    this.ulStyle.height = cellHeight * 7 +'px';
  },
  methods : {
    prevMonth () {
      if (this.time.month === 1) {
        this.time.month = 12;
        this.time.year--;
      } else {
        this.time.month--;
      }
      this.updateCalendar();
    },
    nextMonth () {
      if (this.time.month === 12) {
        this.time.month = 1;
        this.time.year++;
      } else {
        this.time.month++;
      }
      this.updateCalendar();
    },
    updateCalendar () {
      const maxDate = getEndDate(this.time);
      if (this.time.date > maxDate) {
        this.time.date = maxDate;
      }
      this.indent = getStartDay(this.time);
      this.dateNum = getEndDate(this.time);
    },
    clickDate (e) {
      const el = e.currentTarget;
      const i = parseInt(el.getAttribute('data-i'));
      this.time.date = i + 1;
      this.ok();
    },
    ok () { this.callback.ok(this.time); },
    no () { this.callback.no(); },
  },
  computed : {

  },
};
</script>

<style lang="scss" scoped>
@import './calendar.scss';
</style>
